package com.example.springsecurityextraloginfield.filter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public static final String SPRING_SECURITY_FROM_DOMAIN_KEY = "domain";

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals(RequestMethod.POST.toString())) {
            throw new AuthenticationServiceException("Authentication method not support:" + request.getMethod());
        }
        final UsernamePasswordAuthenticationToken token = getAuthRequest(request);
        setDetails(request,token);
        return this.getAuthenticationManager().authenticate(token);
    }

    private UsernamePasswordAuthenticationToken getAuthRequest(HttpServletRequest request){
        String username = obtainUsername(request) == null ? "" : obtainUsername(request);
        String password = obtainPassword(request) == null ? "" : obtainPassword(request);
        String domain = obtainDomain(request) == null ? "" : obtainDomain(request);
        String usernameAndDomain = String.format("%s%s%s",username.trim(),String.valueOf(Character.LINE_SEPARATOR),domain.trim());
        return new UsernamePasswordAuthenticationToken(usernameAndDomain,password);
    }

    private String obtainDomain(HttpServletRequest request){
        return request.getParameter(SPRING_SECURITY_FROM_DOMAIN_KEY);
    }
}
